import { forwardRef, useImperativeHandle, useRef } from "react";

// forwardRef的作用是：让组件拿到子组件的dom
// useImperativeHandle的作用是：让父组件拿到子组件的暴露方法
const Son = forwardRef(function (prop, ref) {
  // 不使用useImperativeHandle
  // return <input ref={ref}></input>;

  // 使用useImperativeHandle 拿到子组件的方法和子组件dom

  const sonref = useRef(null);
  const divRef = useRef(null);
  const Sonfocus = function () {
    sonref.current.focus();
  };
  useImperativeHandle(ref, () => {
    return {
      Sonfocus,
      divRef: divRef.current,
    };
  });
  return (
    <>
      <input type="text" ref={sonref}></input>
      <div ref={divRef}>我是子组件的内容</div>
    </>
  );
});
function Father() {
  const ipt = useRef(null);

  /* eslint-disable no-unused-vars */
  const focus = function () {
    console.log(ipt, ipt.current.divRef);
    // ipt.current.focus();
    ipt.current.Sonfocus();
  };

  return (
    <>
      <div className="list">
        forwardRef的使用
        <button onClick={focus}>子组件聚焦</button>
        <Son ref={ipt}></Son>
      </div>
    </>
  );
}
export default Father;
